package com.changgou.seckill.task;


import com.changgou.common.constant.SeckillConstant;
import com.changgou.common.util.DateUtil;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Scheduled(cron = "0/55 * * * * ?")
    public void loadGoodsToRedis(){
        //获取当前时间及其之后的5个秒杀开始时间；然后再根据条件查询出每个时间段的秒杀商品
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date date : dateMenus) {
            //创建条件对象
            Example example=new Example(SeckillGoods.class);

            //创建查询条件对象
            Example.Criteria criteria = example.createCriteria();

            //已审核
            criteria.andEqualTo("status","1");

            //库存大于0
            criteria.andGreaterThan("stockCount",0);

            //开始时间大于等于当前的秒杀时间段起始时间
            criteria.andGreaterThanOrEqualTo("startTime",date);

            //结束时间小于当前的秒杀时间段起始时间加2小时
            criteria.andLessThan("endTime",DateUtil.addDateHour(date,2));

            //获取当前这个时间段对应字符串格式
            String timeStr = DateUtil.date2str(date, DateUtil.PATTERN_YYYYMMDDHH);


            //这些商品应该是不在redis中的；所以应该排除当前这个时间段已经在redis中的商品
            Set set = redisTemplate.boundHashOps(SeckillConstant.SECKILL_GOODS_PREFIX + timeStr).keys();
            if (set!=null&&set.size()>0){
                criteria.andNotIn("id",set);
            }
            //根据条件查询
            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectByExample(example);
            if (seckillGoodsList!=null&&seckillGoodsList.size()>0){
                for (SeckillGoods seckillGoods : seckillGoodsList) {
                    redisTemplate.boundHashOps(SeckillConstant.SECKILL_GOODS_PREFIX+timeStr).put(seckillGoods.getId(),seckillGoods);
                }
            }
        }
    }
}
